package edu.virginia.cs4501.team22.services;

import java.io.BufferedInputStream;
import java.net.URL;
import java.util.Scanner;

import javax.jws.WebService;


@WebService(targetNamespace = "http://services.team22.cs4501.virginia.edu/", endpointInterface = "edu.virginia.cs4501.team22.services.GetDirectionsEndpoint", portName = "GetDirectionsPort", serviceName = "GetDirectionsService")
public class GetDirections implements GetDirectionsEndpoint {
	public String directionsJSON(int loc_lat, int loc_long, int dest_lat, int dest_long) {
		float myY = new Float(loc_lat);
		myY /=1000000;
		float myX = new Float(loc_long);
		myX /=1000000;
		float desY = new Float(dest_lat);
		desY /=1000000;
		float desX = new Float(dest_lat);
		desX /=1000000;
		return directionsJSON(myY, myX, desY, desX);
	}
	public String directionsJSON(float loc_lat, float loc_long, float dest_lat, float dest_long) {
		String
			loc = "origin=" + loc_lat + "," + loc_long,
			dest = "destination=" + dest_lat + "," + dest_long,
			theJSON = "";
		
		Scanner scan = null;
		try {
			//This URL requests a JSON file containing route information from GoogleMaps
			URL JSON_URL = new URL("http://maps.googleapis.com/maps/api/directions/json?" + loc + "&" + dest + "&mode=walking&sensor=false");
			//Establishes a connection to the file
			BufferedInputStream bin = new BufferedInputStream(JSON_URL.openStream());
			//Read the file
			scan = new Scanner(bin);
			while (scan.hasNext()) {
				theJSON += scan.nextLine() + "\n";
			}
		} catch (Exception e) { 
			theJSON = "{\n\"status\": \"REQUEST_DENIED: " + 
				e + "\",\n\"routes\": [ ]\n}";
		}
		scan.close();
		return theJSON;
	}

	public static void main(String args[]) {
		float lat_1 = 38.036339F;
		float long_1 = -78.505897F;
		float lat_2 = 38.0324F;
		float long_2 = -78.5110F;
		System.out.println(new GetDirections().directionsJSON(lat_1, long_1, lat_2, long_2));
	}
}